'use client'

import { useState } from 'react'
import { MainLayout } from '@/components/layout/main-layout'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Search, User, Activity, Heart, Zap, Moon, Footprints, TrendingUp, Calendar, Filter, BarChart3 } from 'lucide-react'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell } from 'recharts'
import { format } from 'date-fns'

interface HealthData {
  [key: string]: string | number | boolean | string[] | undefined
  onceHeartValue?: string
  heart_rate?: string
  value?: string
  temperature?: string
  Blood_oxygen?: string
  spo2?: string
  isAutoMeasure?: boolean
  hrv?: string
  arraySleepQuality?: string[]
  sleepUnitLength?: string
  duration?: string
  detailMinterStep?: string
  steps?: string
  calories?: string
  distance?: string
}

interface HealthLog {
  id: number
  user_id: number
  type: string
  device_id: string
  data: HealthData
  timestamp: string
  created_at: string
  user: {
    id: number
    mobile: string
    name: string
    avatar?: string
    gender: number
    age: number
    height: string
    weight: string
  }
}

interface QueryResult {
  logs: HealthLog[]
  pagination: {
    page: number
    limit: number
    total: number
    pages: number
  }
}

interface ChartData {
  time: string
  value: number
  type: string
}

const healthTypeMap = {
  heart_rate: { label: '心率', icon: Heart, color: 'bg-red-100 text-red-800', unit: 'bpm', chartColor: '#ef4444' },
  hrv: { label: '心率变异性', icon: Activity, color: 'bg-blue-100 text-blue-800', unit: 'ms', chartColor: '#3b82f6' },
  spo2: { label: '血氧', icon: Zap, color: 'bg-green-100 text-green-800', unit: '%', chartColor: '#10b981' },
  temperature: { label: '体温', icon: TrendingUp, color: 'bg-orange-100 text-orange-800', unit: '°C', chartColor: '#f97316' },
  sleep: { label: '睡眠', icon: Moon, color: 'bg-purple-100 text-purple-800', unit: 'h', chartColor: '#8b5cf6' },
  step: { label: '步数', icon: Footprints, color: 'bg-indigo-100 text-indigo-800', unit: '步', chartColor: '#6366f1' }
}


function HealthQueryContent() {
  const [mobile, setMobile] = useState('')
  const [deviceId, setDeviceId] = useState('')
  const [type, setType] = useState('')
  const [userId, setUserId] = useState('')
  const [loading, setLoading] = useState(false)
  const [queryResult, setQueryResult] = useState<QueryResult | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [viewMode, setViewMode] = useState<'table' | 'chart'>('table')
  const [chartData, setChartData] = useState<ChartData[]>([])
  const [typeStats, setTypeStats] = useState<Array<{name: string, count: number, color: string}>>([])

  const handleSearch = async (page = 1) => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (mobile) params.append('mobile', mobile)
      if (deviceId) params.append('device_id', deviceId)
      if (type && type !== 'all') params.append('type', type)
      if (userId) params.append('user_id', userId)
      params.append('page', page.toString())
      params.append('limit', '50')

      const response = await fetch(`/api/health/query?${params}`)
      const result = await response.json()

      if (result.success) {
        setQueryResult(result.data)
        setCurrentPage(page)
        processChartData(result.data.logs)
        processTypeStats(result.data.logs)
      } else {
        alert(result.message || '查询失败')
      }
    } catch (error) {
      console.error('查询错误:', error)
      alert('查询失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const processChartData = (logs: HealthLog[]) => {
    const data = logs.map((log: HealthLog) => {
      let value = 0
      try {
        const logData = log.data
        switch (log.type) {
          case 'heart_rate':
            value = parseInt(logData.onceHeartValue || logData.heart_rate || logData.value || '0')
            break
          case 'temperature':
            value = parseFloat(logData.temperature || logData.value || '0')
            break
          case 'spo':
          case 'spo2':
            value = parseInt(logData.Blood_oxygen || logData.spo2 || logData.value || '0')
            break
          case 'step':
          case 'steps':
            value = parseInt(logData.detailMinterStep || logData.steps || logData.value || '0')
            break
          case 'sleep':
            if (logData.arraySleepQuality && Array.isArray(logData.arraySleepQuality)) {
              const sleepData = logData.arraySleepQuality
              const unitLength = parseInt(logData.sleepUnitLength || '1')
              const deepSleep = sleepData.filter((q: string) => q === '1').length * unitLength
              const lightSleep = sleepData.filter((q: string) => q === '2').length * unitLength
              const remSleep = sleepData.filter((q: string) => q === '3').length * unitLength
              const totalSleep = deepSleep + lightSleep + remSleep
              value = Math.round(totalSleep / 60 * 10) / 10 // 转换为小时，保留1位小数
            } else {
              value = parseFloat(logData.duration || logData.value || '0')
            }
            break
          default:
            value = parseFloat(logData.value || '0')
        }
      } catch {
        value = 0
      }

      return {
        time: format(new Date(parseInt(log.timestamp)), 'MM-dd HH:mm'),
        value,
        type: log.type
      }
    }).filter(item => item.value > 0).reverse()

    setChartData(data)
  }

  const processTypeStats = (logs: HealthLog[]) => {
    const stats = logs.reduce((acc, log) => {
      const type = log.type
      if (!acc[type]) {
        acc[type] = { name: healthTypeMap[type as keyof typeof healthTypeMap]?.label || type, count: 0, color: healthTypeMap[type as keyof typeof healthTypeMap]?.chartColor || '#666' }
      }
      acc[type].count++
      return acc
    }, {} as Record<string, {name: string, count: number, color: string}>)

    setTypeStats(Object.values(stats))
  }

  const formatTimestamp = (timestamp: string) => {
    try {
      return format(new Date(parseInt(timestamp)), 'yyyy-MM-dd HH:mm:ss')
    } catch {
      return timestamp
    }
  }

  const formatHealthData = (type: string, data: HealthData) => {
    try {
      switch (type) {
        case 'heart_rate':
          return `${data.onceHeartValue || data.heart_rate || data.value || '--'} bpm`
        case 'temperature':
          return `${data.temperature || data.value || '--'} °C`
        case 'spo':
        case 'spo2':
          const bloodOxygen = data.Blood_oxygen || data.spo2 || data.value || '--'
          const isAuto = data.isAutoMeasure !== undefined ? (data.isAutoMeasure ? '自动' : '手动') : ''
          return `${bloodOxygen}% ${isAuto ? `(${isAuto})` : ''}`
        case 'hrv':
          return `${data.hrv || data.value || '--'} ms`
        case 'sleep':
          if (data.arraySleepQuality && Array.isArray(data.arraySleepQuality)) {
            const sleepData = data.arraySleepQuality
            const unitLength = parseInt(data.sleepUnitLength || '1')
            
            // 统计各阶段时长（分钟）
            const deepSleep = sleepData.filter((q: string) => q === '1').length * unitLength
            const lightSleep = sleepData.filter((q: string) => q === '2').length * unitLength
            const remSleep = sleepData.filter((q: string) => q === '3').length * unitLength
            const awake = sleepData.filter((q: string) => q === '5').length * unitLength
            const totalSleep = deepSleep + lightSleep + remSleep
            
            return `总睡眠${Math.round(totalSleep/60*10)/10}h (深睡${deepSleep}min, 浅睡${lightSleep}min, REM${remSleep}min, 清醒${awake}min)`
          }
          return `${data.duration || data.value || '--'} 小时`
        case 'step':
        case 'steps':
          const totalSteps = data.detailMinterStep || data.steps || data.value || '--'
          const calories = data.calories ? `${data.calories}卡` : ''
          const distance = data.distance ? `${data.distance}km` : ''
          const extras = [calories, distance].filter(Boolean).join(', ')
          return `${totalSteps}步 ${extras ? `(${extras})` : ''}`
        default:
          return JSON.stringify(data).substring(0, 50) + '...'
      }
    } catch {
      return '--'
    }
  }

  const getHealthTypeInfo = (type: string) => {
    return healthTypeMap[type as keyof typeof healthTypeMap] || { 
      label: type, 
      icon: Activity, 
      color: 'bg-gray-100 text-gray-800',
      unit: '',
      chartColor: '#666'
    }
  }

  const clearFilters = () => {
    setMobile('')
    setDeviceId('')
    setType('')
    setUserId('')
    setQueryResult(null)
    setChartData([])
    setTypeStats([])
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">健康数据查询</h1>
          <p className="text-sm text-gray-500 mt-1">查询和分析用户健康指标数据</p>
        </div>
        <div className="flex items-center space-x-2">
          <Button
            variant={viewMode === 'table' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('table')}
          >
            <Search className="w-4 h-4 mr-1" />
            表格视图
          </Button>
          <Button
            variant={viewMode === 'chart' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('chart')}
            disabled={!queryResult}
          >
            <BarChart3 className="w-4 h-4 mr-1" />
            图表视图
          </Button>
        </div>
      </div>

      {/* 查询条件 */}
      <Card>
        <CardHeader className="pb-4">
          <CardTitle className="text-lg flex items-center">
            <Filter className="w-5 h-5 mr-2" />
            查询条件
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="space-y-2">
              <Label htmlFor="mobile">手机号</Label>
              <Input
                id="mobile"
                placeholder="输入手机号"
                value={mobile}
                onChange={(e) => setMobile(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="deviceId">设备ID</Label>
              <Input
                id="deviceId"
                placeholder="输入设备ID"
                value={deviceId}
                onChange={(e) => setDeviceId(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="userId">用户ID</Label>
              <Input
                id="userId"
                placeholder="输入用户ID"
                value={userId}
                onChange={(e) => setUserId(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="type">数据类型</Label>
              <Select value={type} onValueChange={setType}>
                <SelectTrigger>
                  <SelectValue placeholder="选择数据类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  {Object.entries(healthTypeMap).map(([key, info]) => (
                    <SelectItem key={key} value={key}>
                      <div className="flex items-center">
                        <info.icon className="w-4 h-4 mr-2" />
                        {info.label}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex items-center space-x-2 mt-4">
            <Button onClick={() => handleSearch(1)} disabled={loading}>
              {loading ? '查询中...' : '查询'}
            </Button>
            <Button variant="outline" onClick={clearFilters}>
              清空条件
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 查询结果统计 */}
      {queryResult && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <BarChart3 className="w-6 h-6 text-blue-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">总记录数</p>
                  <p className="text-2xl font-bold text-gray-900">{queryResult.pagination.total.toLocaleString()}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-green-100 rounded-lg">
                  <User className="w-6 h-6 text-green-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">当前页记录</p>
                  <p className="text-2xl font-bold text-gray-900">{queryResult.logs.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <Calendar className="w-6 h-6 text-purple-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">总页数</p>
                  <p className="text-2xl font-bold text-gray-900">{queryResult.pagination.pages.toLocaleString()}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <TrendingUp className="w-6 h-6 text-orange-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">当前页</p>
                  <p className="text-2xl font-bold text-gray-900">{queryResult.pagination.page}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 数据展示区域 */}
      {queryResult && (
        <>
          {viewMode === 'table' ? (
            /* 表格视图 */
            <Card>
              <CardHeader>
                <CardTitle>查询结果</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b">
                        <th className="text-left p-2">ID</th>
                        <th className="text-left p-2">用户信息</th>
                        <th className="text-left p-2">数据类型</th>
                        <th className="text-left p-2">设备ID</th>
                        <th className="text-left p-2">数值</th>
                        <th className="text-left p-2">记录时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      {queryResult.logs.map((log: HealthLog) => {
                        const typeInfo = getHealthTypeInfo(log.type)
                        const IconComponent = typeInfo.icon
                        return (
                          <tr key={log.id} className="border-b hover:bg-gray-50">
                            <td className="p-2 font-mono text-xs">{log.id}</td>
                            <td className="p-2">
                              <div className="flex items-center space-x-2">
                                <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                                  <User className="w-4 h-4 text-blue-600" />
                                </div>
                                <div>
                                  <p className="font-medium text-sm">{log.user?.name || '未知用户'}</p>
                                  <p className="text-xs text-gray-500">{log.user?.mobile}</p>
                                </div>
                              </div>
                            </td>
                            <td className="p-2">
                              <Badge className={typeInfo.color}>
                                <IconComponent className="w-3 h-3 mr-1" />
                                {typeInfo.label}
                              </Badge>
                            </td>
                            <td className="p-2 font-mono text-xs">{log.device_id}</td>
                            <td className="p-2 font-medium">{formatHealthData(log.type, log.data)}</td>
                            <td className="p-2 text-xs text-gray-500">{formatTimestamp(log.timestamp)}</td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>

                {/* 分页 */}
                {queryResult.pagination.pages > 1 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="text-sm text-gray-500">
                      第 {queryResult.pagination.page} 页，共 {queryResult.pagination.pages} 页
                    </div>
                    <div className="flex space-x-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleSearch(currentPage - 1)}
                        disabled={currentPage <= 1 || loading}
                      >
                        上一页
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleSearch(currentPage + 1)}
                        disabled={currentPage >= queryResult.pagination.pages || loading}
                      >
                        下一页
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          ) : (
            /* 图表视图 */
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 数值趋势图 */}
              {chartData.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>数值趋势</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <LineChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="time" />
                        <YAxis />
                        <Tooltip />
                        <Line 
                          type="monotone" 
                          dataKey="value" 
                          stroke="#3b82f6" 
                          strokeWidth={2}
                          dot={{ fill: '#3b82f6', strokeWidth: 2, r: 4 }}
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>
              )}

              {/* 数据类型分布 */}
              {typeStats.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>数据类型分布</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <PieChart>
                        <Pie
                          data={typeStats}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={(props: any) => `${props.name} ${(props.percent * 100).toFixed(0)}%`}
                          outerRadius={80}
                          fill="#8884d8"
                          dataKey="count"
                        >
                          {typeStats.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip />
                      </PieChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>
              )}

              {/* 数据类型统计柱状图 */}
              {typeStats.length > 0 && (
                <Card className="lg:col-span-2">
                  <CardHeader>
                    <CardTitle>数据类型统计</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <BarChart data={typeStats}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="name" />
                        <YAxis />
                        <Tooltip />
                        <Bar dataKey="count" fill="#3b82f6" />
                      </BarChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </>
      )}

      {/* 空状态 */}
      {!queryResult && !loading && (
        <Card>
          <CardContent className="text-center py-12">
            <Search className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">开始查询健康数据</h3>
            <p className="text-gray-500">请输入查询条件，点击查询按钮获取健康数据</p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

export default function HealthQueryPage() {
  return (
    <MainLayout title="健康数据查询">
      <HealthQueryContent />
    </MainLayout>
  )
}